package web.servlet;

import java.io.File;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import my.util.RenamePolicyCos;

import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.servlet.VelocityLayoutServlet;

import com.oreilly.servlet.MultipartRequest;

public class DoUploadServlet extends VelocityLayoutServlet {

	protected Template handleRequest(HttpServletRequest request,HttpServletResponse response,
									Context ctx) throws Exception{
		
		Template template = this.getTemplate("uploadfinished.vm");

		System.out.println("request.contenttype:"+request.getContentType());
		
		File fileDir = new File(this.getServletContext()  
                .getRealPath("/FileDir"));  
        if (!fileDir.exists()) {  
            fileDir.mkdirs();  
        }  
        // 设置上传文件的大小，超过这个大小 将抛出IOException异常，默认大小是1M。  
        int inmaxPostSize = 10 * 1024 * 1024;  
        MultipartRequest multirequest = null;  
        // 上传文件重命名策略  
        RenamePolicyCos myRenamePolicyCos = new RenamePolicyCos();  
        try {  
            // MultipartRequest()有8种构造函数！  
            multirequest = new MultipartRequest(request, fileDir  
                    .getAbsolutePath(), inmaxPostSize, "GBK", myRenamePolicyCos); // GBK中文编码模式上传文件  
            String subject = multirequest.getParameter("subject");// 获取普通信息  
            System.out.println(subject);  
            Enumeration<String> filedFileNames = multirequest.getFileNames();  
            String filedName = null;  
            if (null != filedFileNames) {  
                while (filedFileNames.hasMoreElements()) {  
                    filedName = filedFileNames.nextElement();// 文件文本框的名称  
                    // 获取该文件框中上传的文件，即对应到上传到服务器中的文件  
                    File uploadFile = multirequest.getFile(filedName);  
                    if (null != uploadFile && uploadFile.length() > 0) {  
                        System.out.println(uploadFile.getName());  
                        System.out.println(uploadFile.getPath());  
                        System.out.println(uploadFile.length());  

                        ctx.put("file", uploadFile.getName());
                    }  
                    // 获取未重命名的文件名称  
                    String Originalname = multirequest  
                            .getOriginalFileName(filedName);  
                    System.out.println(Originalname);  
                }  
            }  
  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        
        ctx.put("upload_dir", "FileDir");
		return template;
	}
}
